<template>
  <div class="anySignMiniCore">
    <md-popup v-model="isPopupShow" position="bottom">
      <div class="md-example-popup md-example-popup-bottom">
        <center>
          <div id="dialog" style=" display:none;">
            <!-- 显示签名区域-->
            <div id="anysign_title">{{signTitle}}</div>
            <div id="container" onmousedown="return false;">
              <canvas id="anysignCanvas" width="2">
              </canvas>
            </div>
            <div id="single_scrollbar" style="text-align: center;  vertical-align:middle; " width="100%">
              <span id="single_scroll_text"> *滑动操作：</span>
              <input id="single_scrollbar_up" type="button" class="button orange" value="左移" />
              <input id="single_scrollbar_down" type="button" class="button orange" value="右移" />
            </div>
            <div id="btnContainerOuter" width="100%">
              <div id="btnContainerInner" style="text-align: center;   font-size:5pt;" width="100%">
                <input id="btnOK" type="button" class="button orange" value="确 定" @click="signSubmit()" />
                <input id="btnClear" type="button" class="button orange" value="清 屏"
                  onclick="javascript:clear_canvas();">
                <input type="button" class="button orange" value="取 消" @click="cancelSign()">
              </div>
            </div>
          </div>
        </center>
        <div id="comment_dialog" style=" display:none;position: fixed;">
          <div id="leftView">
            <p id="comment_title"></p>
            <div id="signImage" class="signImagecss"></div>
          </div>
          <div id="tmpcanvascss" class="tmpcanvascss">
            <div id="signTitle"></div>
            <canvas id="comment_canvas"></canvas>
          </div>
          <div id="comment_btnContainerInner" class="comment_btncontainer">
            <input id="comment_ok" type="button" class="button orange" @click="signSubmit()" value="确 定">
            <input id="comment_back" type="button" class="button orange" value="后退">
            <input id="comment_cancel" type="button" class="button orange" value="取 消" @click="commentCancel()">
          </div>
        </div>
      </div>
    </md-popup>
  </div>
</template>
<script>
  import {
    Toast,
    Popup
  } from 'mand-mobile'
  export default {
    name: 'any-sign',
    components: {
      [Popup.name]: Popup,
    },
    props: {
      signerInfo: {
        type: Object,
        default: function () {
          return {
            userName: null,
            idNo: null
          }
        }
      },
      channel: {
        type: String,
        default () {
          return '10010'
        }
      },
      signTitle: {
        type: String,
        default: '请签名'
      },
      isdistinguish: {
        type: Boolean,
        default: false
      },
      signClass: {
        type: Object,
        default: function () {
          return {
            penColor: '#FF0000',
            singleWidth: 80,
            singleHeight: 80
          }
        }
      },
      templateId: { //用于生成PDF的模板ID
        type: String,
        default: 'T1000000017'
      },
      businessNo: { //集成信手书业务的唯一标识
        type: String,
        default: '123123'
      },
      formData: { //模板文件数据
        type: String,
        default: 'PGh0bWw+PGhlYWQ+PHRpdGxlPjwvdGl0bGU+PG1ldGEgaHR0cC1lcXVpdj0nQ29udGVudC1UeXBlJyBjb250ZW50PSd0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgnIC8+PC9oZWFkPjxib2R5PjxkaXY+PGRpdj48bGFiZWw+a2V5d29yZDo8L2xhYmVsPjwvZGl2PjxkaXY+PGxhYmVsPuWIl+WQjTLvvJo8L2xhYmVsPjwvZGl2PjxkaXY+PGxhYmVsPuWIl+WQjTPvvJo8L2xhYmVsPjwvZGl2PjwvZGl2PjwvYm9keT48L2h0bWw+'
      },
      ocrCapture: { //识别参数
        type: Object,
        default: function () {
          return {
            text: '', //待识别字
            IPAdress: 'http://192.168.126.32:11203/HWR/RecvServlet', //请求地址 https://znrz-stg.jryzt.com:10044/jkins/electronicSignature/ocr http://localhost:8082/esign_ocr
            appID: '123', //应用编码
            count: 5,
            // language : Language.CHS,//语言
            resolution: 80, //分辨率
            serviceID: '999999' //设备编码
          }
        }
      },
    },
    data() {
      return {
        apiInstance: null,
        resources: {
          css: {
            canvas_css: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/css/canvas_css.css',
            sp: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/css/sp.css',
            mw480Portrait: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/css/mw480Portrait.css',
            sw1024: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/css/sw1024.css'
          },
          js: {
            default: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/zlib/deflate.min.js',
            cryptoCore: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/components/core-min.js',
            cryptoSha1: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/rollups/sha1.js',
            cryptoTripledes: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/rollups/tripledes.js',
            cryptoModeEcb: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/components/mode-ecb.js',
            anysignCommentUI: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/anysignCommentUI.js',
            jquery: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/jquery-1.4.2.min.js',
            anysignAll: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/anysign_all.min_2.js',
            anysignWebInterface: 'https://cdn1.huaruisales.com/mobsite/lib/anysign/anysignWebInterface_2.js',
          }
        },
        signInfo: {},
        isPopupShow: false
      }
    },
    created() {
      let _this = this
      if (typeof (window.anysignstartload) == 'undefined') {
        this.anysignstartload = true
        window.anysignstartload = true

        let cssObj = _this.resources.css
        let jsObj = _this.resources.js
        for (const key in _this.resources.css) {
          if (cssObj.hasOwnProperty(key)) {
            const cssUrl = cssObj[key]
            _this.initCss(cssUrl)
          }
        }
        // let sequence = Promise.resolve()
        // Object.keys(jsObj).forEach(jsKey => {
        //   sequence = sequence.then(_this.initJs(jsObj[jsKey])).then(res => {
        //     console.log(jsKey)
        //     return res
        //   })
        // })
        // sequence.then(res => {
        //   console.log(res)
        //   window.loaded = true
        //   _this.initSign()
        // })
        let header = document.getElementsByTagName('head')[0]
        new Promise((resolve, resject) => {
          let src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/zlib/deflate.min.js'
          // let initFlag = this.jsInit(src)
          // if(initFlag){
          //   this.init()
          //   return
          // }
          let script = document.createElement('script')
          script.type = 'text/javascript'
          script.src = src
          header.appendChild(script)
          script.onload = script.onreadystatechange = function () {
            if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
              console.log(1)
              resolve(true)
            }
            script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
          }
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src =
              'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/components/core-min.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(2)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/rollups/sha1.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(3)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src =
              'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/rollups/tripledes.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(4)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src =
              'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/CryptoJS v3.1.2/components/mode-ecb.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(5)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/anysignCommentUI.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(6)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/jquery-1.4.2.min.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(7)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/libs/anysign_all.min.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(8)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          return new Promise((resolve, resject) => {
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://cdn1.huaruisales.com/mobsite/lib/anysign/anysignWebInterface.js'
            header.appendChild(script)
            script.onload = script.onreadystatechange = function () {
              if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
                console.log(9)
                resolve(true)
              }
              script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
            }
          })
        }).then(result => {
          window.loaded = true
          this.initSign()
        })
      } else if (window.anysignstartload == true) {
        setTimeout(function () {
          _this.initSign()
        }, 2000)
      }
    },
    methods: {
      initCss(url) {
        //初始化css
        let link = document.createElement('link')
        link.rel = 'icon'
        link.href = url
        document.body.appendChild(link)
      },
      initJs(jsUrl) {
        return new Promise((resolve) => {
          let script = document.createElement('script')
          let header = document.getElementsByTagName('head')[0]
          script.type = 'text/javascript'
          script.src = jsUrl
          header.appendChild(script)
          script.onload = script.onreadystatechange = function () {
            if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
              resolve(true)
            }
            script.onload.onload = script.onreadystatechange = null //删除事件处理函数。
          }
        })
      },
      initSign() {
        let _this = this
        //识别回调接口
        var identify_callback = function (errCode) {
          if (errCode == '0') {
            return
          }
          if (errCode == '10003') {
            Toast.info('输入数据项无法解析！')
          } else if (errCode == '10011') {
            Toast.info('服务系统异常错误！')
          } else if (errCode == '10100') {
            Toast.info('识别结果为空！')
          } else if (errCode == '10101') {
            Toast.info('连接识别服务超时！')
          } else if (errCode == '10102') {
            Toast.info('连接识别服务异常！')
          } else if (errCode == '-1') {
            Toast.info('书写错误！')
          } else {
            Toast.info('签字识别失败，请稍后再试')
          }
        }
        var callback = function (context_id, context_type, val) {
          if (context_type == 10) {
            //签名回显
            console.log('签名返回：')
            _this.signInfo.signImg = val
          } else if (context_type == 12) {
            //签名回显
            console.log('批注返回：' + val)
            _this.signInfo.commentImg = val
          }
          _this.apiInstance.isReadyToUpload()
          let sign = _this.apiInstance.getUploadDataGram()
          _this.signInfo.signData = sign
          _this.$emit('getSignInfo', _this.signInfo)
        }
        //设置签名算法，默认为RSA，可以设置成SM2
        window.EncAlgType.EncAlg = 'SM2'
        _this.apiInstance = new window.AnySignApi()
        let res = null
        //初始化签名接口
        res = _this.apiInstance.initAnySignApi(callback, _this.channel)
        if (!res) {
          Toast.info('init error')
        }

        //开启识别
        _this.ocrCapture = _this.ocrCapture || new window.OCRCapture()
        _this.setIdentifyCallBack(identify_callback)

        res = _this.addSignatureObj(20)
        if (!res) {
          console.log('addSignatureObj error')
          return
        }
        res = _this.addCommentObj(30)
        //res = testAddCommentObj(31);
        if (!res) {
          return
        }
        //将配置提交
        res = this.apiInstance.commitConfig()

        if (res) {
          console.log('Init ALL 提交配置成功')
        } else {
          console.log('Init ALL 提交配置失败')
        }
        this.setTemplateData()
      },
      setIdentifyCallBack(callback) {
        if (!this.apiInstance) {
          console.log('信手书接口没有初始化')
          return
        }
        this.apiInstance.setIdentifyCallBack(callback)
      },
      setTemplateData() {
        let _this = this
        let res = null
        //配置JSON格式签名原文
        res = _this.apiInstance.setTemplate(window.TemplateType.PDF, _this.formData, _this.businessNo, _this.templateId)

        if (res) {
          console.log('setTemplateData 0')
          _this.$emit('initReady', true)
          return res
        } else {
          console.log('setTemplateData error')
          return res
        }
      },
      //添加单签签名框
      addSignatureObj(contextId) {
        let _this = this
        let signerRule = null
        //必须要真实数据
        let signer = new window.Signer(_this.signerInfo.userName, _this.signerInfo.idNo)
        if (contextId == 20) {
          signerRule = new window.SignRule_XYZ(100.0, 110.1, 180.2, 50.3, 1, 'pt')
        } else {
          signerRule = new window.SignRule_XYZ(100.0, 110.1, 180.2, 50.3, 1, 'pt')
        }
        let signatureConfig = new window.SignatureConfig(signer, signerRule)
        // signatureConfig.timeTag = timeTag;
        signatureConfig.singleWidth = _this.signClass.singleWidth
        signatureConfig.singleHeight = _this.signClass.singleHeight
        signatureConfig.title = _this.signTitle
        signatureConfig.penColor = _this.signClass.penColor
        signatureConfig.isTSS = true //是否开始时间戳服务
        signatureConfig.signatureImgRatio = 3.0
        signatureConfig.nessesary = false
        signatureConfig.isdistinguish = _this.isdistinguish
        signatureConfig.ocrCapture = _this.ocrCapture
        let res = _this.apiInstance.addSignatureObj(contextId, signatureConfig)
        if (res) {
          console.log('addSignatureObj ' + contextId + ' success')
          return res
        } else {
          console.log('addSignatureObj ' + contextId + ' success')
          return res
        }
      },
      addCommentObj(contextId) {
        let _this = this
        let signer = new window.Signer(_this.signerInfo.userName, _this.signerInfo.idNo)
        let signerRule = new window.SignRule_XYZ(84.0, 523.0, 400.0, 477.0, 1, 'dp')
        let commentConfig = new window.CommentConfig(signer, signerRule)
        commentConfig.commitment = '本人已阅'
        commentConfig.mass_word_height = 50
        commentConfig.mass_word_width = 50
        commentConfig.mass_words_in_single_line = 4
        commentConfig.penColor = _this.signClass.penColor
        commentConfig.nessesary = true
        commentConfig.isdistinguish = false
        commentConfig.ocrCapture = _this.ocrCapture
        commentConfig.mass_dlg_type = window.CommentInputType.WhiteBoard
        var res = _this.apiInstance.addCommentObj(contextId, commentConfig)
        if (res) {
          return res
        } else {
          return res
        }
      },
      popupDialog(context_id = 20) {
        if (!this.apiInstance) {
          console.log('信手书接口没有初始化')
          this.initSign()
        }
        this.isPopupShow = true
        switch (this.apiInstance.showSignatureDialog(context_id)) {
          case 0:
            break
          case 1:
            console.log('信手书接口没有初始化')
            break
          case 2:
            console.log('没有配置相应context_id的签字对象')
            break
        }
      },
      commentDialog(context_id = 30) {
        if (!this.apiInstance) {
          console.log('信手书接口没有初始化')
          this.initSign()
        }
        this.isPopupShow = true
        switch (this.apiInstance.showCommentDialog(context_id)) {
          case 0:
            break
          case 1:
            console.log('信手书接口没有初始化')
            break
          case 2:
            console.log('没有配置相应context_id的签字对象')
            break
          case 5:
            console.log('批注签名框已弹出，请勿重复操作！')
        }
      },
      //单字签名取消
      cancelSign() {
        this.isPopupShow = false
        window.cancelSign()
      },
      //批注签名取消
      commentCancel() {
        this.isPopupShow = false
      },
      signSubmit() {
        // console.log(this.apiInstance);
        // let data = this.apiInstance.getEmptyFlag()
        if (!this.apiInstance.getEmptyFlag()) {
          Toast.info('请签名')
          return
        }
        window.sign_confirm()
        this.isPopupShow = false
      }
    }
  }
</script>
<style lang="less" scoped>
  .anySignMiniCore {
    .comment_titlecss {
      font-size: 20px;
      clear: both;
    }

    /deep/.md-popup {
      .md-popup-box {
        background-color: #ffffff;
        height: 100%;
      }
    }

    .comment_btncontainer {
      text-align: center;
      margin: 0 auto;
      font-size: 20px;
      width: 100%;
      clear: both;
      position: absolute;
      bottom: 10;
    }

    .signImagecss {
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      overflow: scroll;
      border: 1px solid rgb(229, 229, 229)
    }

    .tmpcanvascss {
      border: 1px solid rgb(229, 229, 229)
    }

    #signTitle {
      width: 100%;
    }

    #anysign_title {
      width: 100%;
      color: #333333;
    }

    #container {
      border: 1px solid #dddddd;
    }

    .btn_orange {
      font-size: 20pt;
      color: #fef4e9;
      border: solid 1px #da7c0c;
      background: #f78d1d;
      background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
    }
  }
</style>